<!--
 * @Author: your name
 * @Date: 2021-11-10 15:30:28
 * @LastEditTime: 2021-12-05 17:55:27
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\admin\src\views\home\knowledgeQuiz\index.vue
-->
<template>
  <div>
    <div class="search-box">
      <el-card class="box-card">
        <div class="input-box">
          <div class="title-input-box">
            <div>名称:</div>
            <el-input placeholder="请输入知识库名称" v-model="searchVal">
            </el-input>
          </div>
          <div class="title-input-box">
            <div>状态:</div>
            <el-select
              v-model="state"
              placeholder="请选择"
              style="width: 190px; margin-left: 10px"
            >
              <el-option
                v-for="(item, index) in options"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="searchKnowledgeList"
            >搜索</el-button
          >
          <el-button @click="resetVal">重置</el-button>
        </div>
      </el-card>
      <el-card class="main-card">
        <div class="create-box">
          <el-button class="create-btn" type="primary" @click="addDrawer"
            >+ 新建</el-button
          >
        </div>
        <div class="table-box">
          <div
            style="width: 25%; max-width: 25%"
            v-for="item in tableData"
            :key="item.id"
          >
            <a-card style="width: 100%" :bordered="false">
              <img
                slot="cover"
                alt="example"
                :src="item.cover"
                v-if="item.cover"
                style="width: 100%; height: 146px"
              />
              <img
                v-else
                :src="noImg"
                alt=""
                style="width: 100%; height: 146px"
              />
              <template
                slot="actions"
                class="ant-card-actions"
                style="position: absolute; bottom: 0"
              >
                <a-icon
                  key="edit"
                  type="edit"
                  @click="toKnowledgeDetail(item.id)"
                />
                <a-tooltip>
                  <template slot="title">
                    {{ item.state * 1 ? "设为草稿" : "发布线上" }}
                  </template>
                  <i
                    class="iconfont icon-cloud-download"
                    v-if="item.state * 1"
                    @click="changeKnowledgeState(item.id)"
                  ></i>
                  <i
                    class="iconfont icon-cloud-upload"
                    v-else
                    @click="changeKnowledgeState(item.id)"
                  ></i>
                </a-tooltip>
                <a-icon
                  key="setting"
                  type="setting"
                  @click="editDrawer(item)"
                />
                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="delKnowledgeList(item.id)"
                >
                  <el-button slot="reference" style="padding: 0; border: none">
                    <a-icon type="delete"
                  /></el-button>
                </el-popconfirm>
              </template>
              <a-card-meta :title="item.title" :description="item.desc">
              </a-card-meta>
            </a-card>
          </div>
        </div>
        <div class="pagination-box">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageIndex"
            :page-sizes="[8, 16, 24, 32]"
            :page-size="100"
            layout="total, prev, pager, next,sizes"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 抽屉 -->
    <a-drawer
      :title="isEdit ? '更新知识库' : '新建知识库'"
      width="620"
      :visible="visible"
      @close="onClose"
    >
      <a-form
        id="components-form-demo-validate-other"
        :form="form"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 22 }"
      >
        <a-form-item label="名称" :colon="false">
          <a-input v-model="form.title" />
        </a-form-item>
        <a-form-item label="描述" :colon="false">
          <a-textarea :rows="4" style="resize: none" v-model="form.desc" />
        </a-form-item>
        <a-form-item label="评论" :colon="false">
          <a-switch v-model="form.is_allow_comment" />
        </a-form-item>
        <!-- ***************************** -->
        <a-form-item label="封面" :colon="false">
          <el-upload
            drag
            action
            :http-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <template v-if="form.cover">
              <img :src="form.cover" alt="" height="120px" />
            </template>
            <template v-else>
              <i class="el-icon-upload"></i>
              <p class="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
            </template>
          </el-upload>
        </a-form-item>
        <!-- ***************************** -->

        <a-form-item label=" " :colon="false">
          <a-input v-model="form.cover" disabled></a-input>
        </a-form-item>
        <a-form-item label=" " :colon="false">
          <a-button @click="showChildrenDrawer">选择文件</a-button>
        </a-form-item>
      </a-form>
      <a-drawer
        title="文件选择"
        width="800"
        :visible="childrenDrawer"
        @close="onChildrenDrawerClose"
      >
        <div class="box-card">
          <div class="input-box">
            <div class="title-input-box">
              <p>文件名称:</p>
              <a-input placeholder="请输入文件名称" v-model="title"> </a-input>
            </div>
            <div class="title-input-box">
              <p>文件类型:</p>
              <a-input placeholder="请输入文件类型" v-model="type"> </a-input>
            </div>
          </div>
          <div class="search-btn-box">
            <el-button type="primary" @click="searchFile">搜索</el-button>
            <el-button @click="result">重置</el-button>
          </div>
          <div class="upload-box">
            <el-upload
              action
              :http-request="handleUpload"
              :before-upload="beforeUpload"
            >
              <el-button>上传文件</el-button>
            </el-upload>
          </div>
        </div>
        <div class="card-main">
          <div
            style="width: 25%; max-width: 25%"
            v-for="item in ossList"
            :key="item.id"
            @click="valutionInfo(item)"
          >
            <a-card hoverable style="width: 95%">
              <img
                slot="cover"
                alt="example"
                :src="item.url"
                style="width: 100%; height: 150px"
              />
              <a-card-meta :title="item.name">
                <template slot="description"
                  >上传于{{ item.lastModified }}</template
                >
              </a-card-meta>
            </a-card>
          </div>
        </div>
        <a-card>
          <div class="pageination-box">
            <el-pagination
              @size-change="handleSizeChangeOss"
              @current-change="handleCurrentChangeOss"
              :current-page="pageIndex"
              :page-sizes="[8, 12, 24, 36]"
              layout="total, prev, pager, next, sizes"
              :total="ossTotal"
            >
            </el-pagination>
          </div>
        </a-card>
      </a-drawer>
      <div
        :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-button style="margin-right: 8px" @click="onClose"> 取消 </a-button>
        <a-button
          type="primary"
          @click="onSubmit()"
          :disabled="!isEdit && !form.title"
        >
          {{ isEdit ? "更新" : "创建" }}
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import api from "../../../api";
import noImg from "../../../assets/暂无.gif";
import { put, signatureUrl, getFileNameUUID, list, del } from "@/utils/oss.js";

export default {
  data() {
    return {
      fileList: [],
      type: "",
      ossList: [],
      title: "",
      // ******
      noImg,
      tableData: [],
      pageSize: 8,
      pageIndex: 1,
      currSize: 8,
      currIndex: 1,
      state: null,
      searchVal: "",
      total: 0,
      ossTotal: 0,
      visible: false, //一级抽屉开关
      childrenDrawer: false, //二级抽屉开关
      isEdit: false,
      detailInfo: {},
      options: [
        {
          value: 1,
          label: "已发布",
        },
        {
          value: 0,
          label: "草稿",
        },
      ],
      form: { title: "", desc: "", is_allow_comment: false, cover: "" },
    };
  },
  methods: {
    //  自定义上传方法
    beforeUpload(file) {
      return true;
    },
    async handleUpload(option) {
      NProgress.start();
      // // 获取文件的后缀名
      var obj = option.file.name;
      var index = obj.lastIndexOf(".");
      obj = obj.substring(index, obj.length);
      // 生成的文件名，保留文件后缀名，进行拼接
      let objName = getFileNameUUID() + option.file.name;
      // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
      await put(`flieName/${objName}`, option.file).then((res) => {
        this.form.cover = res.url;
        // 上传成功之后，转换真实的地址
        signatureUrl(`flieName/${objName}`).then((res) => {
          console.log(res);
        });
      });
      NProgress.done();
    },
    //获取列表
    async getKnowledgeList() {
      const res = await api.getKnowledgeList({
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
        state: this.state,
        title: this.searchVal,
      });
      if (res.success) {
        this.tableData = res.data.res;
        this.total = res.data.total;
      } else {
        this.$message({
          type: "warning",
          message: res.data,
        });
      }
    },
    //数量切换
    handleSizeChange(val) {
      //设置pageSize
      this.pageSize = val;
      //重新获取数据
      this.getKnowledgeList();
    },
    //页数切换
    handleCurrentChange(val) {
      //设置pageSize
      this.pageIndex = val;
      //重新获取数据
      this.getKnowledgeList();
    },
    //数量切换
    handleSizeChangeOss(val) {
      //设置pageSize
      this.currSize = val;
      //重新获取数据
      this.getOssFile();
    },
    //页数切换
    handleCurrentChangeOss(val) {
      //设置pageSize
      this.currIndex = val;
      //重新获取数据
      this.getOssFile();
    },
    //改变线上状态
    async changeKnowledgeState(id) {
      //调取接口
      const res = await api.changeKnowledgeState({ id });
      if (res.success) {
        //重新渲染
        this.getKnowledgeList();
      }
    },
    // //重置
    result() {
      this.type = "";
      this.title = "";
      this.currSize = 8;
      this.currIndex = 1;
      this.getOssFile();
    },
    //清空各个框 并重新获取数据
    resetVal() {
      this.pageIndex = 1;
      this.state = null;
      this.searchVal = "";
      this.getKnowledgeList();
    },
    //删除
    async delKnowledgeList(id) {
      const res = await api.delKnowledgeList({ id });
      if (res.success) {
        this.getKnowledgeList();
        this.$message({
          type: "success",
          message: "已删除",
        });
      }
    },
    searchKnowledgeList() {
      this.pageIndex = 1;
      this.getKnowledgeList();
    },
    /********/
    //显示抽屉(一级)
    showDrawer() {
      this.visible = true;
    },
    //关闭抽屉(一级)
    onClose() {
      this.visible = false;
    },
    //显示抽屉(二级)
    showChildrenDrawer() {
      this.childrenDrawer = true;
    },
    //关闭抽屉(二级)
    onChildrenDrawerClose() {
      this.childrenDrawer = false;
    },
    editDrawer(data) {
      this.isEdit = true;
      this.form = {
        ...data,
        url: data.cover,
        is_allow_comment: Boolean(data.is_allow_comment * 1), //数字(字符串类型数字)转布尔
      };
      this.showDrawer();
    },
    addDrawer() {
      this.isEdit = false;
      this.form = { title: "", desc: "", is_allow_comment: false, cover: "" };
      this.showDrawer();
    },
    normFile(e) {
      console.log("Upload event:", e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    //提交按钮
    async onSubmit() {
      //判断是否为编辑
      if (this.isEdit) {
        //调用接口
        const res = await api.editKnowledgeList({
          id: this.form.id,
          title: this.form.title,
          state: this.form.data,
          desc: this.form.desc,
          is_allow_comment: Number(this.form.is_allow_comment),
          cover: this.form.cover,
        });
        //重新渲染
        if (res.success) {
          this.getKnowledgeList();
          this.$message({
            type: "success",
            message: "更新成功",
          });
        } else {
          this.$message({
            type: "warning",
            message: "意外的错误",
          });
        }
      } else {
        const res = await api.addKnowledgeList({
          title: this.form.title,
          state: 0,
          desc: this.form.desc,
          is_allow_comment: Number(this.form.is_allow_comment),
          cover: this.form.cover,
        });
        if (res.success) {
          this.$message({
            type: "success",
            message: "创建成功",
          });
          this.getKnowledgeList();
        } else {
          this.$message({
            type: "warning",
            message: "意外的错误",
          });
        }
      }
      this.onClose();
    },
    //获取oss数据
    async getOssFile() {
      //显示加载进度条--->提示用户加载进度
      NProgress.start();
      const res = await list();
      console.log(res);
      this.ossList = res.objects;
      //结束用户加载进度
      this.ossList.sort((a, b) => {
        return new Date(b.lastModified) - new Date(a.lastModified);
      });
      this.ossList = this.ossList.map((item) => {
        return {
          ...item,
          name: item.name.split("flieName/")[1],
          path: item.name,
          type: "image/" + item.name.split(".")[1],
        };
      });
      let newList = this.ossList;
      this.ossTotal = newList.length;
      if (this.title) {
        newList = newList.filter((item) => item.name.includes(this.title));
      }
      if (this.type) {
        newList = newList.filter((item) => item.type.includes(this.type));
      }
      this.ossList = newList.slice(
        (this.currIndex - 1) * this.currSize,
        this.currSize * this.currIndex
      );
      this.ossTotal = newList.length;
      NProgress.done();
    },
    //搜索事件
    searchFile() {
      this.currIndex = 1;
      this.getOssFile();
    },
    //赋值cover封面信息
    valutionInfo(data) {
      this.form = { ...this.form, cover: data.url };
      this.onChildrenDrawerClose();
    },
    toKnowledgeDetail(id) {
      this.$router.push(`/knowledgeDetail/${id}`);
    },
  },
  created() {
    //获取数据
    this.getKnowledgeList();
    //oss数据
    this.getOssFile();
  },
};
</script>

<style lang="scss" scoped>
.search-box {
  width: 95%;
  margin: 0 auto;
  margin-top: 25px;
  margin-bottom: 15px;
  .input-box {
    display: flex;
  }
}
.input-box .title-input-box {
  margin: 0 20px;
  display: flex;
  align-items: center;

  div {
    width: 36px;
  }
  .el-input {
    width: 250px;
    margin-left: 10px;
  }
}
.search-btn {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .el-button {
    height: 35px;
    line-height: 12px;
  }
}
.pagination-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.create-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  .create-btn {
    padding: 10px 20px;
    border-radius: 2px;
  }
}
.main-card {
  margin-top: 20px;
}
.table-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .ant-card {
    padding: 8px;
  }
}
.pre-img {
  width: 100%;
  height: 150px;
  display: inline-block;
  padding: 20px 0;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
}
.box-card {
  width: 100%;
  .input-box {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
}
.input-box .title-input-box {
  display: flex;
  align-items: center;
  p {
    width: 95px;
  }
}
.search-btn-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.card-main {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
  .ant-card {
    padding: 20px;
    border: none;
    margin: 5px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
.pageination-box {
  display: flex;
  justify-content: flex-end;
}
.info-box {
  font-size: 12px;
  margin: 15px 0;
  color: #000;
}
.copy-link {
  display: flex;
  margin-bottom: -30px;
  span {
    width: 55px;
    flex-shrink: 0;
    flex-wrap: wrap;
  }
  p {
    width: 510px;
    flex-shrink: 0;
    border: 1px solid #ccc;
    padding: 5px;
  }
}
.upload-box {
  display: flex;
  justify-content: flex-end;
}
</style>
